package org.fixies.utils;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import static org.fixies.utils.StringUtils.concat;

/**
 * // TODO change this
 * User: Tsuyoshi
 * Date: 2010/11/11
 * Time: 5:07:26
 */
public final class CollectionUtils {

    public static <T> T[] copy(T[] array) {
        return array == null ? null :array.clone();
    }

    public static <T> T[] toArray(Collection<T> orig, Class<T> elementType) {
        if (orig == null) return null;
        @SuppressWarnings("unchecked")
        T[] newArray = (T[]) Array.newInstance(elementType, orig.size());
        return orig.toArray(newArray);
    }


    public static <K, V> Map<K, V> createLRUMap(Map<K, V> orig, final int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException(concat(
                    "argument maxSize must not be less than zero. but was [", maxSize, "]"));
        }
        return new LinkedHashMap<K, V>(orig) {

            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                return size() > maxSize;
            }
        };
    }
    private CollectionUtils() {
    }
}
